<template>
  <view class="container" :style="{ height: showDeletePopup ? 'initial' : '100%' }">
    <!-- 收货地址组件 -->
    <my-address :hintList="hintList" :needAddress="needAddress" :hasRealGoods="hasRealGoods"
      :upperDoor="hasRealGoodsUpperDoor"></my-address>
    <view @click="goShopp" class="order_empty" v-if="!hasCartGoods">
      <view class="empty">您还没有要支付的订单哟!</view>
      <view class="go_shopp">马上去添加</view>
    </view>
    <!-- 商品详情 -->
    <CartGoodsDetail :isPost="isPost" :hasPaidByShipper="hasPaidByShipper" v-if="hasCartGoods" :itemIndex="itemIndex"
      @clickNum="i => itemIndex = i"></CartGoodsDetail>
    <!-- {{ isPrepaidRice }} -->
    <pickup-method :isPost="isPost" v-if="hasRealGoods" :isPrepaidRice="isPrepaidRice" @sendValue="groupChange"
      :hasPaidByShipper="hasPaidByShipper" />
    <view class="card discount_item" v-if="hasCartGoods">
      <text class="name">优惠券</text>
      <text class="num">暂无可用</text>
    </view>
    <view class="card money_item" v-if="hasCartGoods">
      <view class="item">
        <text class="name">商品金额</text>
        <view class="num">￥<text class="text">{{ totalPrice | moneyShow }}</text></view>
      </view>
      <view class="item freight">
        <text class="name">运费</text>
        <view class="num">+￥<text class="text" style="font-weight: 500">{{
          needPostage ? freight + '.00' : 0 + '.00'
        }}</text></view>
      </view>
    </view>
    <template v-if="hasCartGoods">
      <!-- 信息填写 -->
      <view class="card" style="margin-bottom: 0">
        <view class="title_user">{{
          allGoodEntityNo
          ? '上门领取用户信息'
          : allGoodEntity
            ? '其它'
            : hasRealGoodsUpperDoor
              ? '存放卡劵/上门领取用户信息'
              : '存放卡劵的会员用户'
        }}</view>
        <u--form ref="orderRef" labelWidth="65" labelAlign="right" labelPosition="left" :model="orderParma"
          :rules="orderRules">
          <template v-if="needUserInfo">
            <u-form-item label="*姓　名" prop="name">
              <u--input clearable maxlength="10" :adjust-position="false" v-model="orderParma.name"></u--input>
            </u-form-item>
            <u-form-item label="*手机号" prop="phone">
              <u--input clearable maxlength="11" :adjust-position="false" type="number"
                v-model="orderParma.phone"></u--input>
            </u-form-item>
            <u-form-item :label="vehicleModelRequired ? '*车型' : '车型'" prop="customer_model" v-if="vehicleModelState">
              <u--input clearable maxlength="20" :adjust-position="false"
                v-model="orderParma.customer_model"></u--input>
            </u-form-item>
            <!-- {{ orderParma.vin_no }} -->
            <u-form-item label="* 车牌号" prop="vin_no">
              <!-- <view v-show="false">
                <u--input v-model="orderParma.vin_no"></u--input>
              </view> -->
              <!-- 车牌号 -->
              <PicensePlateNumber ref="picense" @carIdVal="carIdVal"></PicensePlateNumber>
            </u-form-item>
          </template>
          <u-form-item label="推荐人" v-if="isReferrer">
            <!-- v-if="Object.keys(shareInfo).length" -->
            <u--input :value="referrer" :adjust-position="false" disabled></u--input>
          </u-form-item>
          <u-form-item label="服务门店">
            <u--input :value="currComInfo.company_name" :adjust-position="false" disabled></u--input>
          </u-form-item>
          <u-form-item label="备　注">
            <u--textarea maxlength="200" placeholder="请输入备注" v-model="orderParma.remarks"></u--textarea>
          </u-form-item>
        </u--form>
      </view>
      <view class="radio_box">
        <u-checkbox-group>
          <u-checkbox activeColor="#de4141" @change="change"> </u-checkbox>
        </u-checkbox-group>
        <view>
          我已阅读、理解并同意此<text @click="openRules" class="policy">《隐私政策》</text>。</view>
      </view>
      <view class="bom_box">
        <!-- <label @click="checkboxChange">
          <radio
            label="全选"
            color="#dd444c"
            :checked="allGoodState"
            style="transform: scale(0.7)"
          ></radio>
          全选</label
        > -->
        <view class="money_box">
          应付金额：
          <text class="num">￥{{ payTotalPrice | moneyShow }}</text>
        </view>
        <view class="btn" @click="submit">立即支付</view>
      </view>
      <view style="height: 140rpx"></view>
    </template>
    <!-- 政策组件 -->
    <RulesCompany ref="rule"></RulesCompany>
    <!-- 登录组件 -->
    <UserLoginModal costomBack ref="openLogin" @loginSuccss="loginSuccss" @costomBack="goShopp"></UserLoginModal>
    <!-- 当前公司没有的商品组件 -->
    <LtemDeleted ref="deletedGoods" @hasNeedDelete="hasNeedDelete"></LtemDeleted>
  </view>
</template>

<script>
import _ from 'lodash'
import MyAddress from '@/Shop/components/MyAddress'
import PickupMethod from '@/Shop/components/PickupMethod'
import { mapState, mapMutations, mapGetters } from 'vuex'
import {
  userPayApi,
  addressListApi,
  addGoodsOrderApi,
  getServiceNameApi
} from '@/API/Shop'
export default {
  name: 'GoodsPay',
  components: { MyAddress, PickupMethod },
  data() {
    return {
      isNew: false,
      isPost: true,
      freight: 20,
      itemIndex: -1,
      orderRules: {
        name: {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        },
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value)
            },
            message: '请输入正确的手机号码',
            trigger: ['change', 'blur']
          }
        ],
        vin_no: [
          {
            type: 'string',
            required: true,
            message: '请输入车牌号'
            // trigger: ['blur', 'change']
          },
          {
            validator: (rule, value, callback) => {
              return this.isNew ? value.length === 8 : value.length === 7
            },
            message: '请输入正确的车牌号'
          }
        ],
        customer_model: [
          {
            validator: (rule, value, callback) => {
              return this.vehicleModelRequired ? value.length > 0 : true
            },
            message: '请输入车型'
          }
        ]
      },
      checkedVal: false,
      showDeletePopup: true,
      orderParma: {
        name: '',
        phone: '',
        // phone: '15920303048',
        wx_name: '',
        vin_no: '',
        remarks: '', //备注
        other: '',
        customer_model: '',
      },
      baseUrl: this.$baseUrl,
      shareInfo: {},
      // 推荐人
      referrer: ''
    }
  },
  computed: {
    ...mapGetters(['currComInfo', 'totalPrice']),
    ...mapState(['centers', 'goodsOrder', 'brandInfo', 'loginInfo', 'address']),
    // 有团购的商品，显示推荐人
    isReferrer() {
      let { telphone: tel } = this.shareInfo
      return tel && tel != 'null' && this.referrer != 'null'
      // let { telphone } = this.loginInfo //根据登录信息判断
      // return telphone && tel !== 'null'
    },
    // 推荐人信息
    referrerInfo() {
      // let { telphone } = this.loginInfo
      let { telphone: tel } = this.shareInfo
      if (tel && tel != 'null') {
        return { telphone: tel }
      }
      return { telphone: '' }
    },
    // 购物车不为空
    hasCartGoods() {
      let goodsOrder = this.goodsOrder
      return goodsOrder.length > 0
    },
    // 都是实体
    allGoodEntity() {
      let selectedProduct = this.selectedProduct
      if (selectedProduct.length == 0) return false
      return selectedProduct.every(item => item.service < 3)
    },
    // 都是实体
    allGoodEntityNo() {
      let selectedProduct = this.selectedProduct
      if (selectedProduct.length == 0) return false
      return selectedProduct.every(item => item.service < 3) && !this.isPost
    },
    // 选中的产品
    selectedProduct() {
      let goodsOrder = this.goodsOrder
      return goodsOrder.filter(item => item.select)
    },
    // 是否要填车型
    vehicleModelState() {
      let selectedProduct = this.selectedProduct
      if (selectedProduct.length == 0) return false
      return selectedProduct.some(item => item?.customer_model?.state === true)
    },
    // 车型是否必填
    vehicleModelRequired() {
      let selectedProduct = this.selectedProduct
      if (selectedProduct.length == 0) return false
      return selectedProduct.some(item => item?.customer_model?.required === true)
    },
    // 选中的产品有不是订金，或不是卡券
    isPrepaidRice() {
      let selectedProduct = this.selectedProduct
      return selectedProduct.some(item => !item.prepaid_rice)
    },
    // 默认选择状态
    defaultSelect() {
      let selectedProduct = this.selectedProduct
      if (selectedProduct.length == 0) return [false]
      // 全部都是包邮
      let flag1 = selectedProduct.every(item => item.service == 1 || item.service == 4)
      if (flag1) {
        return [flag1]
      }
      // 全部都是不包邮
      let flag2 = selectedProduct.every(item => item.service == 2 || item.service == 4)
      if (flag2) {
        return [flag1, flag2]
      }
      // 有不包邮,并且是订金
      let flag3 = selectedProduct.some(item => item.service == 2 && item.prepaid_rice)
      if (flag3) {
        return [flag1, flag2, flag3]
      }
      // 有不包邮,并且不是订金
      let flag4 = selectedProduct.some(item => item.service == 2 && !item.prepaid_rice)
      if (flag4) {
        return [flag1, flag2, flag3, flag4]
      }
    },
    // 选中的产品含有的产品类型（去重）
    allGoodType() {
      let temp = []
      let selectedProduct = this.selectedProduct
      temp = selectedProduct.map(item => item.type_name1)
      return [...new Set(temp)]
    },
    // 选择的有实商品
    hasRealGoods() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service < 3)
    },
    // 选择的有实商品，并是上门领
    hasRealGoodsUpperDoor() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service < 3) && !this.isPost
    },
    // 有寄付
    hasPaidByShipper() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service == 2)
    },
    // 是否要收货地址
    needAddress() {
      let hasRealGoods = this.hasRealGoods
      return hasRealGoods && this.isPost
    },
    // 是否有:不包邮,并要邮寄
    isNeedPost() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service == 2) && this.isPost
    },
    // 是否有:不包邮,并要邮寄,并不是订金付款
    needPostage() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service == 2 && !item.prepaid_rice) && this.isPost
    },
    // 是否要填用户信息
    needUserInfo() {
      let goodsOrder = this.selectedProduct
      return goodsOrder.some(item => item.service > 2) || !this.isPost
    },
    // 到店领取实品提示信息
    hintList() {
      let selectedProduct = this.selectedProduct
      // 实体
      let temp1 = selectedProduct.filter(item => item.service < 3)
      let temp2 = temp1.map(item => item.type_name1)
      let temp3 = [...new Set(temp2)]
      let compaName = `${this.currComInfo?.company_name}-`
      let temp = temp3.map((item, index) => {
        if (item === '精品专场') {
          return { info: `*精品专场商品,请到<${compaName}精品部>!`, id: index }
        }
        if (item === '精品-改装专场') {
          return { info: `*精品-改装专场商品,请到<${compaName}精品部>!`, id: index }
        }
        if (item === '精品改装专场') {
          return { info: `*精品改装专场商品,请到<${compaName}精品部>!`, id: index }
        }
        if (item === '销售专场') {
          return { info: `*销售专场商品,请到<${compaName}销售前台>!`, id: index }
        }
        if (item === '售后专场') {
          return { info: `*售后专场商品,请到<${compaName}售后服务中心>!`, id: index }
        }
      })
      return temp
    },
    // 加上运费的支付价格
    payTotalPrice() {
      let freight = this.freight
      let totalPrice = this.totalPrice
      if (this.needPostage) {
        return (totalPrice * 10 * 10 + freight * 10 * 10) / 100
      } else {
        return totalPrice
      }
    },

  },
  watch: {
    isReferrer: {
      handler(newVal) {
        if (!newVal) return
        if (this.referrer != '') return
        this.getServiceName()
      },
      deep: true,
      immediate: true
    },
    defaultSelect: {
      handler(newV) {
        console.log('watchwatch',)
        let [flag1, flag2, flag3, flag4] = newV
        if (flag1) {
          this.isPost = true
        } else if (flag2) {
          this.isPost = false
        } else if (flag3) {
          this.isPost = true
        } else if (flag4) {
          this.isPost = false
        }
      },
      immediate: true
    },
  },
  mounted() {
    if (this.hasCartGoods) {
      this.$refs.orderRef.setRules(this.orderRules)
    }
  },
  methods: {
    carIdVal(v) {
      this.isNew = v.isNew
      this.orderParma.vin_no = v.carId
    },
    groupChange(v) {
      this.isPost = v
    },
    // 去商店
    goShopp() {
      uni.switchTab({
        url: `/pages/Shop/ShopAdmin`
      })
    },
    ...mapMutations([
      'updateAddress',
      'updateGoodsOrderPay',
      'saveCarModelDataList',
      'changeGoodsNub', //更改购物车商品数量
      'updateGoodsState',
    ]),
    // 添加订单
    async submit() {
      // this.createOrder()
      // return
      if (this.needAddress && Object.keys(this.address).length == 0) {
        return uni.$showMsg('请先选择收货地址！')
      }
      if (!this.checkedVal) {
        return uni.$showMsg('请阅读并同意勾选协议')
      }
      this.$refs.orderRef
        .validate()
        .then(async req => {
          // const [err, res] = await uni.login().catch(err => err)
          // if (err || res.errMsg !== 'login:ok')
          //   return uni.$showMsg('获取code失败！')
          // this.callUserPay()
          this.createOrder('', 2, this.callUserPay)
        })
        .catch(errors => {
          uni.$showMsg('信息请填写完整！')
        })
    },
    // 创建订单
    async createOrder(v_id, state, cb) {
      // 选择的商品
      let deepValue = _.cloneDeep(this.selectedProduct)
      let { uuid, nickName } = this.loginInfo
      let temp = this.orderParma
      let address = this.address
      // 支付价格，加上运费的
      let payTotalPrice = this.payTotalPrice
      // 是否要收货地址
      let needAddress = this.needAddress
      // 是否有:不包邮,并要邮寄
      let isNeedPost = this.isNeedPost
      let needUserInfo = this.needUserInfo
      let shareInfo = this.referrerInfo
      let isReferrer = this.isReferrer
      let { brand_id } = this.brandInfo
      let { id } = this.currComInfo
      let post = ''
      // console.log(total)
      deepValue.forEach(item => {
        if (
          item.coupon_list &&
          item.coupon_list !== '[]' &&
          item.coupon_list !== 'null'
        ) {
          let tempCoupons = JSON.parse(item.coupon_list).filter(item =>
            item.company_id == id)
          // 卡券功能未开发
          tempCoupons[0].itemMoney = item.price - 0 / deepValue.length
          item.coupon_list = JSON.stringify(tempCoupons)
        }
        post = item.service // 商品服务类型
        item.company_id = id
        item.brand_id = brand_id
        item.name = needUserInfo ? temp.name : ''
        item.phone = needUserInfo ? temp.phone : ''
        item.wx_name = needUserInfo ? nickName : ''
        item.vin_no = temp.vin_no
        item.shop_num = item.num
        item.price_discount = 0 //优惠
        item.price_paid = payTotalPrice //支付总价
        item.price_transport = post == 2 && isNeedPost ? 20 : 0 //运费
        item.remarks = temp.remarks //备注
        item.other = temp.other
        item.itemMoney = item.price - item.price_discount / deepValue.length
        item.uuid = uuid
        item.referrer = isReferrer ? shareInfo?.telphone : ''
        item.demo = true
        item.post_service = this.orderService(post)
        item.address = needAddress ? JSON.stringify(address) : '{}' //地址
        item.state = state === 2 ? 2 : post > 3 ? 1 : needAddress ? 3 : 3
        item.customer_model = temp.customer_model
      })
      console.log('deepValue', deepValue)
      // return
      const {
        data: { v_id: vId, code, message }
      } = await addGoodsOrderApi({
        v_id,
        list: deepValue
      })
      // return
      if (code == 400) return uni.$showMsg(`${message}`)
      if (code === 200) {
        // 发起微信支付
        cb && cb(vId)
      }
    },
    // 生成订单号
    async callUserPay(vId) {
      const [err, res] = await uni.login().catch(err => err)
      if (err || res.errMsg !== 'login:ok')
        return uni.$showMsg('获取code失败！')
      let title = this.allGoodType.join(',')
      let { brand } = this.brandInfo //(只有这里用品牌字母)
      let { id } = this.currComInfo
      let param = {
        title,
        v_id: vId,
        brand,
        code: res.code,
        company_id: id,
        price: this.payTotalPrice
      }
      const { data } = await userPayApi(param)
      if (data.code == 400) return uni.$showMsg(`${data.message}`)
      if (data.status == 403) return uni.$showMsg('支付订单失败，请联系门店客服！')
      if (data.status != 200) return uni.$showMsg('支付订单创建失败！')
      console.log('支付', data)
      let { paySign, nonceStr, signType, appId, timeStamp } = data
      // 发起微信支付
      let payInfo = {
        paySign,
        nonceStr,
        signType,
        timeStamp,
        provider: appId,
        orderInfo: vId,
        package: data.package
      }
      this.requestPayment(vId, payInfo)
    },
    // 发起微信支付
    async requestPayment(vId, payInfo) {
      const [err, succ] = await uni.requestPayment(payInfo)

      // 清空购物车已购买的商品
      this.updateGoodsOrderPay()
      //  清空分享信息
      uni.setStorageSync('shareInfo', JSON.stringify({}))
      let sta = 1
      // 未完成支付
      if (err) {
        sta = 2
        this.toOrderAdmin(sta, 0)
      } else {
        uni.showToast({
          title: '支付成功',
          duration: 1500,
          icon: 'success'
        })
        // 完成支付,修改订单状态
        // this.createOrder(vId, 1)
        this.toOrderAdmin(sta, 1700)
      }
      // return
    },
    toOrderAdmin(sta, time = 0) {
      setTimeout(() => {
        // 到订单列表页
        uni.redirectTo({
          url: `/Shop/OrderAdmin?state=${sta}`
        })
      }, time)
    },
    //订单服务
    orderService(post) {
      if (post == 1 && this.isPost) {
        return 1
      }
      if (post == 1 && !this.isPost) {
        return 3
      }
      if (post == 2 && this.isPost) {
        return 5
      }
      if (post == 2 && !this.isPost) {
        return 3
      }
      return 4
    },
    // 调用子组件方法
    openRules() {
      this.$refs.rule.openRul()
    },
    change(e) {
      this.checkedVal = e
    },
    async getServiceName() {
      let { brand_id } = this.brandInfo
      let { telphone } = this.referrerInfo
      let { id: company_id } = this.currComInfo
      const { data } = await getServiceNameApi({ telphone, brand_id, company_id })
      this.referrer = data.data
    },
    // 收货地址列表
    async getAddressList(uuid) {
      const { data } = await addressListApi({ uuid })
      // console.log('地址列表', data)
      if (data.data.length > 0) {
        this.updateAddress(data.data[0])
      }
    },
    loginSuccss(v) {
      this.orderParma.phone = v.phoneNumber
    },
    hasNeedDelete(v) {
      this.showDeletePopup = v.flag
    },

  },
  onLoad(options) {
    this.shareMixin.title = `订单确认`
    this.shareMixin.path = `/pages/Shop/ShopAdmin`
    this.shareInfo =
      JSON.parse(uni.getStorageSync('shareInfo') || '{}')?.shareInfo || {}

    let loginInfo = this.loginInfo
    // 是否登录
    if (!Object.keys(loginInfo).length) {
      this.$refs.openLogin.isShow()
      return false
    }

    this.$refs.deletedGoods.getNeedDeleteGoods()
    let { uuid, phoneNumber = '' } = loginInfo
    if (!Object.keys(this.address).length) {
      // 地址列表
      this.getAddressList(uuid)
    }
    this.orderParma.phone = phoneNumber
  },
  onPageScroll() {
    this.itemIndex = -1
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/mixins.scss';

::v-deep .u-radio-group {
  max-width: 340rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

::v-deep .uni-swipe_button-group {
  margin-bottom: 30rpx;
}

::v-deep .u-form-item {
  position: relative;
}

// ::v-deep .u-input {
//   position: relative;
//   height: initial; // 固定高度
//   overflow-y: auto; // 超出滚动
//   overscroll-behavior: initial; // 禁止滚动溢出
// }

::v-deep .u-form-item__body__right__message {
  position: absolute;
  top: 98rpx;
}

::v-deep .u-form-item__body {
  padding: 15px 0 !important;
}

::v-deep .u-form-item__body__right__message {
  line-height: 30px !important;
}

.order_empty {
  margin: 0rpx auto;
  padding: 80rpx 0;
  text-align: center;

  .empty {
    font-size: 32rpx;
  }

  .go_shopp {
    line-height: 66rpx;
    font-size: 32rpx;
    color: $theme-color;
    font-weight: bold;
  }
}

.card {
  width: 92%;
  padding: 10px;
  margin: 0 auto 30rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: $theme-shadow2;
}

.container {
  background-color: #f8f9f8;
  position: relative;
  overflow-y: scroll; // 超出滚动
  overscroll-behavior: none; // 禁止滚动溢出

  .search_box {
    background-color: #fff;
    padding: 20rpx 0;
    border-bottom: 1px solid #f1f1f1;

    .search {
      display: flex;
      align-items: center;
      width: 90%;
      margin: 0 auto;
      padding: 16rpx 25rpx;
      border-radius: 3px;
      background-color: #f1f1f1;
      font-size: 24rpx;
      color: #999;
    }
  }

  .money_item {
    .item {
      display: flex;
      justify-content: space-between;
      line-height: 48rpx;

      .name {
        color: #222;
        font-weight: 600;
        font-size: 30rpx;
        line-height: 52rpx;
      }

      .num {
        font-size: 26rpx;
        font-weight: 500;

        .text {
          color: #222;
          font-weight: 600;
          font-size: 32rpx;
        }
      }
    }

    .freight {
      .num {
        .text {
          font-size: 30rpx;
        }
      }
    }
  }

  .discount_item {
    display: flex;
    justify-content: space-between;
    line-height: 48rpx;

    .name {
      color: #222;
      font-weight: 600;
      font-size: 28rpx;
    }

    .num {
      color: #666;
      font-weight: 500;
      font-size: 28rpx;
    }
  }

  // 存放卡劵的会员用户
  .title_user {
    padding: 10rpx 0 20rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #222;
    text-align: center;
  }

  .bom_box {
    position: fixed;
    z-index: 99;
    bottom: 0;
    width: 100%;
    padding: 30rpx 40rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    border-top: 2rpx solid rgba(0, 0, 0, 0.09);

    .money_box {
      font-size: 30rpx;
      color: #777;

      .num {
        font-size: 34rpx;
        font-weight: bold;
        color: $theme-color;
      }
    }

    .btn {
      width: 220rpx;
      line-height: 80rpx;
      text-align: center;
      background-color: $theme-color;
      border-radius: 8rpx;
      color: #f8f9f8;
    }
  }
}

// 隐私政策
.radio_box {
  margin: 0 auto;
  padding-bottom: 120rpx;
  padding-top: 30rpx;
  width: 91%;
  display: flex;
  justify-content: flex-start;

  .policy {
    color: $theme-color;
  }
}
</style>
